package infra.framework.common.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import infra.framework.common.dao.BaseDao;
import infra.framework.common.domain.info.BaseInfo;
import infra.framework.common.domain.param.BaseParam;
import infra.framework.common.domain.result.PageInfo;
import infra.framework.common.service.BaseService;
import lombok.Data;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by wangweilin on 2018/10/29.
 */
@Data
public abstract class AbstractBaseService<R, Q extends BaseParam, D extends BaseDao<R, Q>, I extends BaseInfo> implements BaseService<R, Q, I> {

    private D dao;

    protected abstract I convert(R r);

    public I getByPrimaryKey(Long id) {
        R r = getDao().getByPrimaryKey(id);
        return convert(r);
    }

    public I get(R record) {
        R r = getDao().get(record);
        return convert(r);
    }

    public int deleteByPrimaryKey(Long id) {
        return getDao().deleteByPrimaryKey(id);
    }

    public int del(R record) {
        return getDao().del(record);
    }

    public int delByCondition(R record) {
        return getDao().delByCondition(record);
    }

    public List<I> listByCondition(Q query) {
        List<R> list = getDao().findByCondition(query);
        return list.stream().map(this::convert).collect(Collectors.toList());
    }

    @Override
    public PageInfo<I> findByCondition(Q query) {
        Page<R> page = PageHelper.startPage(query.getPageNo(), query.getPageSize());
        List<I> list = listByCondition(query);
        return PageInfo.newInstance(page, list);
    }

    public int findTotalCount(Q query) {
        return getDao().findTotalCount(query);
    }

    public int save(R record) {
        return getDao().save(record);
    }

    public int saveSelective(R record) {
        return getDao().saveSelective(record);
    }

    public int saveBatch(List<R> record) {
        return getDao().saveBatch(record);
    }

    public int updateByPrimaryKeySelective(R record) {
        return getDao().updateByPrimaryKeySelective(record);
    }

    public int update(R record) {
        return getDao().update(record);
    }
}
